﻿using GalaSoft.MvvmLight.Command;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows.Input;
using TabbedTemplate.Models;
using TabbedTemplate.Services;
using Xamarin.Forms;

namespace TabbedTemplate.ViewModels
{
    public class QueryPageViewModel : INotifyPropertyChanged
    {
        /// <summary>
        /// 依赖服务。
        /// </summary>
        private IStoreService _storeService;

        private IPreferenceStorage _preferenceStorage;

        private IPunchNavigationService _punchNavigationService;

        private IQueryService _queryService;

        private ILocationService _locationService;

        private string _input;


        public string Input
        {
            get { return _input; }
            set { _input = value; }
        }

        /// <summary>
        /// 热门搜索。
        /// </summary>
        private List<string> _hotSearchList;

        public List<string> HotSearchList
        {
            get { return _hotSearchList; }
            set { _hotSearchList = value; }
        }

        private List<string> _searchHistoryList;

        public List<string> SearchHistoryList
        {
            get { return _searchHistoryList; }
            set { _searchHistoryList = value; }
        }


        public QueryPageViewModel(IStoreService storeService,
            IPreferenceStorage preferenceStorage,
            IPunchNavigationService punchNavigationService, IQueryService queryService, ILocationService locationService)
        {
            _storeService = storeService;
            _preferenceStorage = preferenceStorage;
            _punchNavigationService = punchNavigationService;
            _locationService = locationService;
            _queryService = queryService;
            Input = "";
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void NotifyPropertyChanged(
            [CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this,
                new PropertyChangedEventArgs(propertyName));
        }

        public ICommand PerformSearch =>
            new Command<string>(async (string query) =>
                await PerformSearchCommandFunction(query));

        public async Task PerformSearchCommandFunction(string query)
        {
            ClassifySearchParameter classifySearchParameter =
                new ClassifySearchParameter
                {
                    Tag = "",
                    Input = query
                };
            await _punchNavigationService.NavigateToAsync(
                ContentNavigationConstant.QueryResultPage, classifySearchParameter);
            Input = "";
            NotifyPropertyChanged($"Input");
        }


        //热门搜索点击。
        private RelayCommand<object> _tappedHotSearch;

        public RelayCommand<object> TappedHotSearch =>
            _tappedHotSearch ??= new RelayCommand<object>(async (tagName) => await TappedHotSearchFunction(tagName));

        public async Task TappedHotSearchFunction(object tagName)
        {
            var tag = "";
            if (tagName != null)
            {
                tag = tagName.ToString();
            }

            var cityName = _preferenceStorage.Get("City", "北京市");

            var res = await _queryService.GetSearchItemByString(tag, cityName);
            //如果历史没有搜索过，tag存入数据库
            if (!res.HasCache)
            {
                await _queryService.InsertSearchItem(tag, cityName);
            }

            ClassifySearchParameter c = new ClassifySearchParameter
            {
                Tag = "",
                Input = tag
            };
            await _punchNavigationService.NavigateToAsync(
                ContentNavigationConstant.QueryResultPage, c);
        }

        //搜索历史点击
        private RelayCommand<object> _tappedHisSearch;

        public RelayCommand<object> TappedHisSearch =>
            _tappedHisSearch ??= new RelayCommand<object>(async (tagName) => await TappedHisSearchFunction(tagName));

        public async Task TappedHisSearchFunction(object tagName)
        {
            var tag = "";
            if (tagName != null)
            {
                tag = tagName.ToString();
            }

            var cityName = _preferenceStorage.Get("City", "北京市");

            ClassifySearchParameter c = new ClassifySearchParameter
            {
                Tag = "",
                Input = tag
            };
            await _punchNavigationService.NavigateToAsync(
                ContentNavigationConstant.QueryResultPage, c);
        }

        private RelayCommand _pageAppearingCommand;

        public RelayCommand PageAppearingCommand =>
            _pageAppearingCommand ??= new RelayCommand(async () => await PageAppearingCommandFunction());

        //加载热搜
        //加载搜索历史(可以存在偏好存储里面)
        //加载搜索发现（暂定）
        public async Task PageAppearingCommandFunction()
        {
            if (!_queryService.Initialized())
            {
                await _queryService.InitializeAsync();
            }

            //TODO 从数据库加载历史列表，调用方法即可。
            var res = await _queryService.GetTenItems();
            SearchHistoryList = res.Select(p => p.SearchContent).ToList();
            var cityName = _preferenceStorage.Get("City", "北京市");
            var stores = await _storeService.GetHotStoresFromWebAsync(cityName);
            HotSearchList = stores.Select(p =>
            {
                var index = p.Name.IndexOf('(');
                if (index == -1)
                {
                    return p.Name;
                }
                return p.Name.Substring(0, index);
            }).ToList();

            NotifyPropertyChanged($"HotSearchList");
            NotifyPropertyChanged($"SearchHistoryList");
        }
    }
}
